package ar.com.viajes.actions;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.actions.DispatchAction;

import ar.com.viajes.dao.PasajeroDao;
import ar.com.viajes.dao.imp.PasajeroDaoImpl;
import ar.com.viajes.dominio.Login;
import ar.com.viajes.dominio.Pasajero;
import ar.com.viajes.form.LoginForm;
import ar.com.viajes.services.ServiceFacade;
import ar.com.viajes.services.SpringUtil;

public class LoginAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		HttpSession session=request.getSession(true); 		
		LoginForm loginf = (LoginForm) form;
		ServiceFacade facade =(ServiceFacade)SpringUtil.getBean("serviceFacade");
		
		List<Pasajero> pasajeros = facade.getPasajeroDao().getAll();

		Login login =  (Login)SpringUtil.getBean("login");
		login.setNombre(Integer.parseInt(loginf.getNombre()));
		login.setPassword(loginf.getPassword());

		boolean bande = false;
		boolean band1 = false;
		
	
		

		for (Pasajero pasajero : pasajeros) {
			if (login.getNombre() == pasajero.getDni()) 
			{
				session.setAttribute("idPasaj",pasajero.getId_pasajero()); 
			
				
				bande = true;
			}

			if (login.getPassword().equals(pasajero.getPassword())) {
				 
					session.setAttribute("idPasajero",pasajero.getId_pasajero()); 
				band1 = true;
				
			}

		}

		if (bande == true && band1 == true) {

			return mapping.findForward("login");
		} else {
			
			 ActionErrors errors = new ActionErrors();
		     errors.add("accessError", new ActionMessage("label.login.novalido"));
		     this.addErrors(request, errors);
		    
        return mapping.findForward("fail");
		}
		
	
		
		
	}

}
